<template>
  <view class="bookdetail">
    <!-- 书籍基本信息 -->
    <Header :book-info="bookInfo" :loading="loading" />
    <!-- 书籍详细信息 -->
    <Detail :text="bookInfo.des" />
    <!-- 订阅书籍 -->
    <Subscription
      v-if="!loading && showSubscript"
      :rss.sync="bookInfo.hasRss"
      :bookid="bookid"
      @close="closeSubscript"
    />
    <!-- 书籍评论 -->
    <Comments :bookid="bookid" />
    <!-- 书籍推荐 -->
    <Recommends v-if="bookid" key-str="book" :extra="{ bookid }" />
    <!-- 下载app -->
    <PageFooter />
  </view>
</template>

<script>
import Header from './components/Header';
import Detail from './components/Detail';
import Subscription from './components/Subscription';
import Comments from './components/Comments';
import Recommends from '@/components/Recommend';
import PageFooter from '@/components/PageFooter';
import { DEFAULT_BOOK_IMAGE } from '@/config.js';
import { mapGetters } from 'vuex';
import { setPageTitle } from '@/utils';

export default {
  components: {
    Header,
    Detail,
    Subscription,
    Comments,
    Recommends,
    PageFooter,
  },

  data() {
    return {
      bookid: '',
      bookInfo: {},
      loading: true,
      showSubscript: false,
    };
  },

  computed: {
    ...mapGetters(['userInfo', 'hasLogin', 'settings', 'autoSecretCode']),
  },

  async onLoad(option) {
    // 隐藏分享按钮
    // #ifndef H5
    uni.hideShareMenu();
    // #endif

    if (!option.id) {
      uni.showToast({ title: '页面参数错误', icon: 'none' });
      return false;
    }
    this.bookid = option.id;

    // 获取书籍信息
    this.fetchBookDetail();

    // 自动解锁
    if (option.pre_secret) {
      if (this.hasLogin) {
        this.preCheckOpen(option.pre_secret);
      } else {
        this.preCheckLoginTips(option.pre_secret);
      }
      return;
    }

    // 检查是否存在share_code参数，如果有则发放分享奖励
    if (option.share_code) {
      if (this.hasLogin) {
        // 登陆了就领奖
        this.updateShareLog(option.share_code);
      } else {
        this.updateShareLoginTips(option.share_code);
      }
    }
  },

  onShareAppMessage(res) {
    const shareCodeParams = this.userInfo.shareCode
      ? `&share_code=${`${this.userInfo.shareCode}@${Date.now()}`}`
      : '';
    const autoSecretParams = this.autoSecretCode
      ? `&pre_secret=${this.autoSecretCode}`
      : '';
    const params = this.autoSecretCode ? autoSecretParams : shareCodeParams;
    return {
      title: `推荐给你一本好书-《${this.bookInfo.name}》`,
      path: `/pages/bookdetail/index?id=${this.bookid}${params}`,
    };
  },

  methods: {
    fetchBookDetail() {
      this.$http({
        method: 'GET',
        url: '/api/front/bookdetail',
        data: {
          id: this.bookid,
        },
        needAuth: true,
        skipToast: false,
        errorText: '获取书籍详情失败',
      }).then((res) => {
        if (res.ok && res.data) {
          const bookName = res.data.name || '未命名';
          this.bookInfo = {
            _id: res.data._id,
            id: res.data._id,
            imgUrl: res.data.img_url || DEFAULT_BOOK_IMAGE,
            img_url: res.data.img_url || DEFAULT_BOOK_IMAGE,
            name: bookName,
            author: res.data.author || '无名大侠',
            alias: res.data.alias || '无',
            status: res.data.update_status || '更新中',
            newestChapter: res.data.newest_chapter || 1,
            des: res.data.des,
            classification: res.data.classification || '默认',
            updateTime: res.data.update_time,
            goodInfo: res.data.good || { type: 'free' },
            unlocked: !!res.data.unlocked,
            isInList: !!res.data.isInList,
            hasRss: !!res.data.rss,
            bookid: res.data,
          };
          setPageTitle(bookName);
          this.loading = false;
          // 是否展示订阅书籍消息
          const noMoreShowSubscriptBooks =
            uni.getStorageSync('noMoreShowSubscriptBooks') || [];
          if (noMoreShowSubscriptBooks.indexOf(this.bookid) > -1) {
            this.showSubscript = false;
          } else {
            this.showSubscript = true;
          }
        }
      });
    },

    closeSubscript() {
      this.showSubscript = false;
    },

    updateShareLog(shareCode) {
      this.$http({
        method: 'GET',
        url: '/api/front/share/update',
        data: {
          share_code: shareCode,
        },
        needAuth: true,
        skipToast: false,
        errorText: '发放分享奖励失败',
      }).then((res) => {
        if (res.ok) {
          this.$store.commit(
            'showSuccessTips',
            `获得${res.data.amount}书币\r\n分享奖励`
          );
        }
      });
    },

    updateShareLoginTips(shareCode) {
      // 没登录引导登陆
      uni.showModal({
        title: '温馨提示',
        content:
          '你已获得系统发放的15书币奖励，书币需要您登陆之后才能领取，点击确认前往登陆页',
        success: (res) => {
          if (res.confirm) {
            const redirect = encodeURIComponent(
              `/pages/bookdetail/index?id=${this.bookid}&share_code=${shareCode}`
            );
            uni.navigateTo({
              url: `/pages/login/index${
                redirect ? `?redirect=${redirect}&type=redirectTo` : ''
              }`,
            });
          } else if (res.cancel) {
            uni.showToast({
              icon: 'none',
              title: '分享奖励还未领取哦~',
            });
          }
        },
      });
    },

    preCheckOpen(preCheckCode) {
      this.$http({
        method: 'POST',
        url: '/api/front/secret/pre_secret_open',
        data: {
          pre_secret: preCheckCode,
        },
        needAuth: true,
        skipToast: true,
      }).then((res) => {
        if (res.ok) {
          this.$store.commit('showSuccessTips', `你已解锁该书籍\n开始阅读吧~`);
        } else {
          if (res.data && res.data.isSelf) return;
          uni.showToast({
            icon: 'none',
            title: res.msg || '自动解锁书籍失败',
          });
        }
      });
    },

    preCheckLoginTips(preCheckCode) {
      // 没登录引导登陆
      uni.showModal({
        title: '温馨提示',
        content: '你需要登陆之后才能解锁该书籍，点击确认前往登陆页',
        success: (res) => {
          if (res.confirm) {
            const page = `/pages/bookdetail/index?id=${this.bookid}&pre_secret=${preCheckCode}`;
            const redirect = encodeURIComponent(page);
            const url = `/pages/login/index${
              redirect ? `?redirect=${redirect}&type=redirectTo` : ''
            }`;
            uni.navigateTo({
              url,
            });
          } else if (res.cancel) {
            uni.showToast({
              icon: 'none',
              title: '书籍还未解锁哦~',
            });
          }
        },
      });
    },
  },
};
</script>

<style lang="scss">
page {
  background: $page-color-base;
}

.bookdetail {
  &__head {
    height: 434rpx;
    overflow: hidden;
    position: relative;

    &-bg {
      filter: blur(28rpx) brightness(60%);
      height: 110%;
      width: 110%;
      margin-top: -28rpx;
      margin-left: -28rpx;
      background-position: center center !important;
      background-size: 100% !important;
    }
  }
}
</style>
